package logic

import (
	"errors"
	"fmt"
	"time"
	"whale/internal/app/admin/consts/req"
	"whale/internal/app/admin/consts/res"
	"whale/internal/app/admin/model"
	"whale/internal/models"
	"whale/internal/repository"
	"whale/pkg/jwt"
	"whale/pkg/utils"
)

// generate logic *LoginLogic  ILoginLogic
type ILoginLogic interface {
	// 登录操作
	LoginPost(data req.LoginReq, ip string) (interface{}, error)
}

func (logic *LoginLogic) LoginPost(data req.LoginReq, ip string) (interface{}, error) {
	var accountInfo model.Account

	if _, err := logic.Repository.Table(&model.Account{}).Where("`account` = ? or `mobile` = ?", data.Account, data.Account).Get(&accountInfo); err != nil {
		return nil, errors.New("登录账号不存在")
	}

	if accountInfo.Status != 1 {
		return nil, errors.New("账号已经被禁用")
	}

	if accountInfo.VerfiyNum >= 5 {
		return nil, errors.New("登录错误次数已超过5次，请联系管理员")
	}

	if utils.PasswordMd5ToString(data.Password, accountInfo.Salt) != accountInfo.Password {
		// 更新登录次数
		var updateData = model.Account{
			LoginIp:   ip,
			LoginNum:  accountInfo.LoginNum + 1,
			LoginAt:   models.XormTime(time.Now()),
			VerfiyNum: accountInfo.VerfiyNum + 1,
		}
		// 增加日志
		logic.Repository.Table(&model.Account{}).Where("id = ?", accountInfo.ID).Update(&updateData)
		return nil, fmt.Errorf("登录密码错误，剩余验证次数%d", 5-updateData.VerfiyNum)
	}
	// 验证成功
	token, err := jwt.GenerateJwtToken(accountInfo.ID, accountInfo.NickName)
	if err != nil {
		return nil, errors.New("登录失败")
	}
	var info = res.LoginRes{
		Token:     token,
		AdminName: accountInfo.NickName,
		Headimg:   accountInfo.Headimg,
		Auth:      accountInfo.Authorize,
	}
	return info, nil
}

type LoginLogic struct {
	Repository repository.IRepository `bean:"Repository"`
}
